import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { useUserInfoStoreWithOut } from '@/stores/modules/userInfo';
import { message } from 'ant-design-vue';
import router from '@/router';

const useUserInfoStore = useUserInfoStoreWithOut();
const http = axios.create({
  baseURL: import.meta.env.VITE_GLOB_API_URL_PREFIX,
  timeout: 10000,
});
// 请求发送拦截
http.interceptors.request.use((config: AxiosRequestConfig) => {
  const { getToken } = storeToRefs(useUserInfoStoreWithOut());
  if (getToken.value) {
    // @ts-expect-error
    config.headers['token'] = getToken.value;
  }
  // @ts-expect-error
  config.headers['Content-Type'] = 'application/json; charset=utf-8';
  return config;
});
// 请求返回拦截
http.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response;
    if (response.headers.token) {
      useUserInfoStore.setToken(response.headers.token);
    }
    if (data.status > 199 && data.status < 300) {
      return data;
    } else {
      errorHandle(response);
      return data;
    }
  },
  // 请求失败
  (error: any) => {
    const { response } = error;
    if (response) {
      // 请求已发出，但是不在2xx的范围
      errorHandle(response);
      return Promise.reject(response.data);
    } else {
      message.error('网络连接异常，请稍后再试');
    }
  }
);

function errorHandle(res: any) {
  // 返回的状态码
  const status = res.data.status;
  const msg = res.data.msg;
  let errorMessage = '';
  switch (status) {
    case 400:
      errorMessage = msg;
      break;
    case 401:
      errorMessage = '用户没有权限，请重新登录';
      useUserInfoStore.logOut();
      break;
    case 403:
      errorMessage = '没有权限访问';
      useUserInfoStore.logOut();
      break;
    case 404:
      errorMessage = '找不到资源';
    case 405:
      errorMessage = '请求方法不被允许';
      break;
    case 408:
      errorMessage = '请求超时';
      break;
    case 422:
      errorMessage = res.data.msg;
      break;
    case 500:
      errorMessage = '服务器内部错误';
      break;
    case 501:
      errorMessage = '网络未实现';
      break;
    case 502:
      errorMessage = '网络错误';
      break;
    case 503:
      errorMessage = '服务不可用';
      break;
    case 504:
      errorMessage = '网络超时';
      break;
    default:
      errorMessage = '未知错误';
  }
  if (errorMessage) {
    if (errorMessage === '账号未登录或登录过期！') {
      useUserInfoStore.logOut();
      router.push({ name: 'login' });
    }
    message.error(errorMessage);
  } else {
    router.replace('/login');
  }
}

export default http;
